﻿using System;
using System.Text;
using static System.Security.Cryptography.MD5;
using static System.StringComparer;
using static System.Text.Encoding;

namespace CommLib.Security
{
    public static class Md5Encrypt
    {
        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="encryptString">要加密的字符串</param>
        /// <param name="code">16or32(不填为32)</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <exception cref="System.Reflection.TargetInvocationException"></exception>
        /// <exception cref="EncoderFallbackException"></exception>
        /// <returns></returns>
        public static string GetMd5Hash(string encryptString, int code = 32)
        {
            if (string.IsNullOrEmpty(encryptString))
                return null;
            string result;
            
            using (var md5 = Create())
            {
                if (md5 == null)
                    return null;
                var source = md5.ComputeHash(UTF8.GetBytes(encryptString));
                switch (code)
                {
                    default:
                        var sBuilder = new StringBuilder();
                        foreach (var s in source)
                        {
                            sBuilder.Append(s.ToString("x2"));
                        }
                        result = sBuilder.ToString();
                        break;
                    case 16:
                        result = BitConverter.ToString(source, 4, 8).Replace("-", "");
                        break;
                }
            }

            return result;
        }

        /// <summary>
        /// 验证md5数据
        /// </summary>
        /// <param name="encryptString">未加密字符串</param>
        /// <param name="hash">加密字符串</param>
        /// <param name="code">16or32(不填为32)</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <exception cref="System.Reflection.TargetInvocationException"></exception>
        /// <exception cref="EncoderFallbackException"></exception>
        /// <returns></returns>
        public static bool VerifyMd5Hash(string encryptString, string hash, int code = 32) => 0 == CurrentCultureIgnoreCase.Compare(GetMd5Hash(encryptString,code), hash);
       
    }
}
